
package com.segment.dcore.servlet;

import com.segment.dcore.base.component.ContextIDGenerator;
import com.segment.dcore.base.constants.ServiceConstants;
import com.segment.dcore.base.filter.ServiceFilterRegister;
import com.segment.dcore.base.service.KCoreService;
import com.segment.dcore.base.utils.ContextIdUtil;
import com.segment.dcore.servlet.filter.context.ServletInvokeContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * ServletFilter
 *
 * Created by huapeng.hhp on 2017/2/27.
 */
public class ServletFilter implements Filter {
	/** 业务执行组件 */
	private KCoreService kcoreService = ServiceFilterRegister
			.getFilterRegisterService(ServiceConstants.SERVLET_FILTER_REGISTER_SERVICE);
	/** 请求ID生成器 */
	private ContextIDGenerator contextIDGenerator = ContextIDGenerator.getContextIDGenerator();

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		// 初始化调用上下文
		final ServletInvokeContext invokeContext = new ServletInvokeContext();
		invokeContext.setRequest(servletRequest);
		invokeContext.setResponse(servletResponse);
		invokeContext.setChain(filterChain);
		String methodName = ((HttpServletRequest) servletRequest).getRequestURI().trim().replaceAll("//*", "/");
		String requestId = null;
		Integer depth = null;
		Integer order = null;
		ContextIdUtil.ProvideContextIdAndDepth(methodName, requestId, depth, order, contextIDGenerator,
				new ContextIdUtil.RequestInvoke<Boolean>() {
					public Boolean doInvoke(final String requestId, final Integer depth, final Integer order) {
						kcoreService.doService(invokeContext);
						return true;
					}
				});
	}

	@Override
	public void destroy() {
	}
}
